import { ConfigEnv, defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import postcssRemToResponsivePixel from 'postcss-rem-to-responsive-pixel'
import postcssWeappTailwindcssRename from 'weapp-tailwindcss-webpack-plugin/postcss'
import vwt from 'weapp-tailwindcss-webpack-plugin/vite'

const isH5 = process.env.UNI_PLATFORM === 'h5'
const isApp = process.env.UNI_PLATFORM === 'app'
const weappTailwindcssDisabled = isH5 || isApp

const postcssPlugin = [autoprefixer(), tailwindcss()]
if (!weappTailwindcssDisabled) {
    postcssPlugin.push(
        postcssRemToResponsivePixel({
            rootValue: 32,
            propList: ['*'],
            transformUnit: 'rpx'
        })
    )
    postcssPlugin.push(postcssWeappTailwindcssRename())
}

const viteConfig = defineConfig((mode: ConfigEnv) => {
    const env = loadEnv(mode.mode, process.cwd())
    return {
        plugins: [uni(), weappTailwindcssDisabled ? undefined : vwt()],
        css: {
            postcss: {
                plugins: postcssPlugin
            }
        },
        server: {
            port: 8088,
            hmr: true, // 启用热更新
            proxy: {
                '/api': {
                    target: env.VITE_APP_BASE_URL, // 目标服务器地址
                    changeOrigin: true // 是否修改请求头中的 Origin 字段
                },
                '/mobile/admin': {
                    target: env.VITE_APP_BASE_URL, // 目标服务器地址
                    changeOrigin: true, // 是否修改请求头中的 Origin 字段
                    rewrite: (path) => path.replace(/^\/mobile/, '')
                }
            }
        }
    }
})

// https://vitejs.dev/config/
export default viteConfig
